package org.example.forum.services.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.UserMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.User;
import org.example.forum.services.IUserService;
import org.example.forum.utils.MD5Util;
import org.example.forum.utils.StringUtil;
import org.example.forum.utils.UUIDUtil;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    //用户注册
    public void createNormalUser(User user){
        //1.非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            //为空打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString()));

        }
        //2.按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        if(existsUser!= null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS.toString()));
        }

        //3.新增用户 设置默认值
        user.setDeleteState((byte)0);
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);

        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //4.写入数据库
        int row = userMapper.insertSelective(user);
        if( row != 1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE.toString()));
        }

        //新增成功，打印日志
        log.info("新用户成功. username = " + user.getUsername() + ". ");

    }

    @Override
    public User selectByUserName(String username) {
        //非空校验
        if(username.isEmpty()){
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE).toString());
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1.非空校验
        if(username.isEmpty() || password.isEmpty()){
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE).toString());
        }
        //2.对用户名进行非空校验
        User user = selectByUserName(username);

        //3.对查询结果做非空校验
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", username = " + username);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //4.密码是否一致
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        // 5. 用密文和数据库中存的用户密码进行比较 排除大小写
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", 密码错误, username = " + username);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 打印登录成功的日志
        log.info("登录成功, username = " + username);
        // 登录成功，返回用户信息
        return user;
        
    }

    @Override
    public User selectById(Long id) {
        if(id == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO查询用户
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //对用户进行非空校验
        if(id == null || id <=0){
            //打印日志
            log.info(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS + " ,user id:"+id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));

        }
        //帖子数加一 需创建一个新的user 避免更新所有值
        User updateUser = new User();
        //设置要更新的属性
        updateUser.setId(user.getId());
        //帖子数加一
        updateUser.setArticleCount(user.getArticleCount()+1);
        //动态更新
        int row= userMapper.updateByPrimaryKeySelective(updateUser);
        //校验一些变更的数量是否为1 为1正常不为1 错误
        if(row != 1 ){
            log.warn(ResultCode.FAILED+"受影响的行数不为1"+" ,id: "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断减1之后，用户的发帖数是否小于0
        if (updateUser.getArticleCount() < 0) {
            // 如果小于0，则设置为0
            updateUser.setArticleCount(0);
        }

        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }



    @Override
    public void modifyInfo(User user) {
        //非空校验
        if(user == null || user.getId() == null || user.getId() <=0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser == null){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义标志位
        boolean checkAttr = false;  //false表示校验未通过
        //定义更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        
        //校验每一个参数并赋值
        //不为空且不与原来的值相同才进行更新
        if(!StringUtil.isEmpty(user.getUsername())
            && user.getUsername()!= updateUser.getUsername()){
            // 需要更新用户名(登录名)时，进行唯一性的校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            //校验修改的用户名在表中是否存在
            if(checkUser!= null){
                // 打印日志
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                // 抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = true;

        }

        //校验用户昵称
        if(!StringUtil.isEmpty(user.getNickname())
            && updateUser.getNickname() != user.getNickname())  {
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }

        //校验用户性别
        if (user.getGender() != null && user.getGender() != existsUser.getGender()) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            // 更新标志位
            checkAttr = true;
        }

        //校验用户电话
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            // 设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            // 更新标志位
            checkAttr = true;
        }

        //校验用户邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            // 设置电话号码
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            checkAttr = true;
        }
        //  校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            // 设置电话号码
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = true;
        }
        // 根据标志位来决定是否可以执行更新
        if (checkAttr == false) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 12. 调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        

    }


//
//    @Override
//    public void modifyPassword(Long id, String newPassword, String oldPassword) {
//        // 非空校验
//        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
//            // 打印日志
//            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            // 抛出异常
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
//        }
//        // 查询要用户信息
//        User user = userMapper.selectByPrimaryKey(id);
//        // 校验用户是否存在
//        if (user == null || user.getDeleteState() == 1) {
//            // 打印日志
//            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
//            // 抛出异常
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
//        }
//        // 校验老密码是否正确
//        // 对老密码进行加密，获取密文
//        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
//        // 与用户当前的密码进行比较
//        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
//            // 打印日志
//            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            // 抛出异常
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
//        }
//
//        // 生成一个新的盐值
//        String salt = UUIDUtil.UUID_32();
//        // 生成新密码的密文
//        String encryptPassword = MD5Util.md5Salt(newPassword, salt);
//
//        // 构造要更新的对象
//        User updateUser = new User();
//        updateUser.setId(user.getId()); // 用户Id
//        updateUser.setSalt(salt); // 新生成的盐
//        updateUser.setPassword(encryptPassword); // 新密码对应的密文
//        Date date = new Date();
//        updateUser.setUpdateTime(date); // 更新时间
//
//        // 调用DAO
//        int row = userMapper.updateByPrimaryKeySelective(updateUser);
//        if (row != 1) {
//            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
//        }
//
//    }
    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if(id == null || id <=0
                || StringUtil.isEmpty(newPassword)
                ||StringUtil.isEmpty(oldPassword)){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取用户信息
        User user = userMapper.selectByPrimaryKey(id);
        //用户是否存在
        if(user == null || user.getDeleteState() == 1){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

//        // 校验老密码是否正确
//        // 对老密码进行加密，获取密文
//        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
//        // 与用户当前的密码进行比较
//        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
//            // 打印日志
//            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            // 抛出异常
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
//        }



        //密码是否一致
        //获取盐
        String salt = user.getSalt();
        //对输入的旧密码进行加密
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword,salt);
        //校验加密后的旧密码是否与数据库中的一致
        if(!oldEncryptPassword.equals(user.getPassword()) ){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //生成一个随机盐值
        String newSalt = UUIDUtil.UUID_32();
        //为新密码加密
        String newEncryptPasssword = MD5Util.md5Salt(newPassword,newSalt);
        //创建一个更新对象
        User updateUser = new User();
        //更新数据
        updateUser.setId(user.getId());
        updateUser.setSalt(newSalt);
        updateUser.setPassword(newEncryptPasssword);
        //写入数据
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //校验写入的数据是否合法
        if(row != 1){
            // 打印日志
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));

        }

    }


}
